<template>
  <div class="home" ref="containerRef"></div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from "vue";
import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { Event, ZeroFactor } from "three";

export default defineComponent({
  props: {
    name: String,
  },
  setup(props) {
    const containerRef = ref<HTMLDivElement>();
    const draw = async () => {
      if (!containerRef.value) {
        return;
      }
      let scene = new THREE.Scene(),
        clickAbleObj:
          | THREE.Object3D<THREE.Event>[]
          | THREE.Mesh<THREE.BoxGeometry, THREE.MeshLambertMaterial>[] = [];
      //初始化loader
      const gtlfLoader = new GLTFLoader(),
        dracoLoader = new DRACOLoader();
      dracoLoader.setDecoderPath("/draco");
      dracoLoader.setDecoderConfig({ type: "js" });
      gtlfLoader.setDRACOLoader(dracoLoader);
      //加载外部的模型文件
      let model = await gtlfLoader.loadAsync("/models/duck/duck.gtlf");
      console.log(model);
      model.scene.position.set(0, 0, 0);
      model.scene.name = "duck";
      //   model.scene.scale.set(30, 30, 30);
      scene.add(model.scene);
      /**
       * 光源设置
       */
      //点光源
      let point = new THREE.PointLight(0xffffff);
      point.position.set(0, 0, 35); //点光源位置
      point.lookAt(0, 0, 0);
      scene.add(point); //点光源添加到场景中
      //环境光
      let ambient = new THREE.AmbientLight(0x444444);
      let axisHeler = new THREE.AxesHelper(300);
      scene.add(axisHeler);
      scene.add(ambient);
      // console.log(scene)
      // console.log(scene.children)
      /**
       * 相机设置
       */
      let width = window.innerWidth; //窗口宽度
      let height = window.innerHeight; //窗口高度
      let k = width / height; //窗口宽高比
      let s = 200; //三维场景显示范围控制系数，系数越大，显示的范围越大
      //创建相机对象
      let camera = new THREE.PerspectiveCamera(60, k, 1, 1000);
      camera.position.set(0, 0, 7); //设置相机位置
      //   camera.up.y = 0;
      //   camera.up.z = 1;
      //   camera.up.x = 0;
      camera.lookAt(model.scene.position); //设置相机方向(指向的场景对象)
      camera.aspect = k;
      camera.updateProjectionMatrix()

      /**
       * 创建渲染器对象
       */
      let renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setSize(width-100, height - 200,false); //设置渲染区域尺寸
      renderer.setClearColor(0xb9d3ff, 1); //设置背景颜色
      containerRef.value.appendChild(renderer.domElement); //body元素中插入canvas对象
      //执行渲染操作   指定场景、相机作为参数
      function render() {
        renderer.render(scene, camera);
      }
      render();
      let controls = new OrbitControls(camera, renderer.domElement); //创建控件对象
      controls.addEventListener("change", render); //监听鼠标、键盘事件
      const canvas = containerRef.value.querySelector('canvas');
      if(!canvas){
          return
      }
      canvas.addEventListener("click", (event: MouseEvent) => {
        event.preventDefault();
        if (!containerRef.value) {
          return;
        }
        let boundClientRect = canvas.getBoundingClientRect(),
          x = ((event.clientX - boundClientRect.left) / canvas.offsetWidth) * 2 - 1,
          y = -((event.clientY - boundClientRect.top) / canvas.offsetHeight) * 2 + 1;
        let standardVector = new THREE.Vector2(x, y);
        let raycaster = new THREE.Raycaster();
        raycaster.setFromCamera(standardVector, camera);
        let intersects = raycaster.intersectObjects(model.scene.children, true);
        if(intersects.length){
            alert('你戳到鸭子了啊，小心点')
        }
      });
    };
    onMounted(() => {
      draw();
    });
    return { containerRef };
  },
});
</script>
<style lang="less">
canvas{
  width: 100%;
}
</style>
